# -*- coding: utf-8 -*-
#   mes基础Model
# @Time    ： 2023/1/30  17:46
# @Auther  ： 徐良
# File     :  baseModel.py

from PySide6.QtCore import QAbstractTableModel, QModelIndex, Qt, Signal
from baseClass.baseRecord import BaseRecord
from share.baseFunction import getInstanceType


class BaseModel(QAbstractTableModel):
    """
    可编辑的基础model
    """
    def __init__(self):
        super(BaseModel, self).__init__()
        self.dirty = False
        self.listDel = set()
        self.listUpdate = set()  # 保存更改记录的hash值
        self.insertFlag = 0
        self.ROB = 0  # 红蓝字， 0为蓝字，1为红字
        self.__records = []
        self.__record = []
        self.fieldList = []
        self.fieldValList = []  # 字段的默认值

    def flags(self, index):
        if not index.isValid():
            return Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled

        return Qt.ItemFlags(QAbstractTableModel.flags(self, index) | Qt.ItemIsEditable)

    def removeRows(self, position, rows=1, index=QModelIndex()):
        self.beginRemoveRows(QModelIndex(), position, position + rows - 1)
        self.__records = (self.__records[:position] + self.__records[position + rows:])
        self.endRemoveRows()
        self.dirty = True
        return True

    def query(self, model):
        super(BaseModel, self).__init__()  # 必须调用父类初始化方法，否则不显示数，不知原因
        self.__records.clear()
        self.records.clear()
        self.load(model)
        self.dirty = False
        self.listDel.clear()
        self.listUpdate.clear()

    def rowCount(self, index=QModelIndex()):
        return len(self.__records)

    @property
    def records(self):
        return self.__records

    def record(self, num):
        if 0 <= num < self.rowCount():
            return self.__records[num]
        else:
            return None

    def addRecord(self, record):
        super(BaseModel, self).__init__()
        self.__records.append(record)

    def getItem(self, row):
        return self.record[row]

    def clearAll(self):
        self.removeRows(0, self.rowCount(), QModelIndex())

    def load(self, model):

        rows = model.rowCount()
        col = model.columnCount()
        for i in range(0, rows):
            fieldValList = []
            rr = []
            for j in range(0, col):
                val = model.record(i).value(self.fieldList[j])

                if getInstanceType(val) == 'QDate':
                    val = val.toString("yyyy-MM-dd")
                elif getInstanceType(val) == 'QDateTime':
                    val = val.toString("yyyy-MM-dd hh:mm:ss")

                fieldValList.append(val)
                rr.append(val)
            r = BaseRecord(self.fieldList, fieldValList)

            self.records.append(r)
        self.dirty = False

    def getDataList(self):
        """
        将model中的数据转换成带中文字段名称的列表
        :return:
        """

        rLists = []     # 全部记录列表
        r = []          # 记录列表
        rLists.append(self.fieldNameList)   # 加入表头
        for i in range(0, len(self.records)):
            for j in range(0, len(self.fieldList)):
                v = self.records[i].__dict__[self.fieldList[j]]
                r.append(str(v))
            rLists.append(r)
            r = []
        return rLists

    def checkFieldExist(self, fieldName):
        lowercase_elements = [element.lower() for element in self.fieldList]
        return fieldName.lower() in lowercase_elements



